package cn.edu.ren.controller;

import cn.edu.ren.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.List;

/**
 * @PackageName: cn.edu.ren.controller
 * @ClassName: UserController
 * @Description:
 * @author: RZS
 * @date: 2021/5/19  20:57
 */
@Controller
public class UserController {
    @GetMapping("/info")
    public String info(Model model){
        User person = new User();
        model.addAttribute("person", person);
        return "user_info";
    }

    @PostMapping("/save")
    public String save(@Valid User person, BindingResult result, Model model){
        System.err.println("访问成功");
        System.err.println(person.toString());

        if (result.hasErrors()) {
            List<ObjectError> lists = result.getAllErrors();
            for (ObjectError error : lists) {
                System.out.println(error.getDefaultMessage());
            }
            model.addAttribute("person", person);

            return "user_info";
        }
        //数据保存。。。
        model.addAttribute("success","校验通过，数据已保存");
        return "success";
    }
}
